#include "simplebinding.h"

#include "../arc.h"
#include "../expression.h"
#include "../expressions/expressioncommon.h"
#include "../place.h"
#include "../transition.h"
#include "binding.h"
#include "bindingalgorithmhelper.h"

#include <QtCore/QList>

using namespace wfnet;

SimpleBinding::SimpleBinding() : IBindingAlgorithm()
{

}

SimpleBinding::~SimpleBinding()
{

}

bool SimpleBinding::bind(Binding& binding,
    const core::BasicTime& globalClock,
    core::BasicTime& proposedGlobalClock,
    const QSet<const Arc* >& inputArcs,
    const Transition* transition) const
{
    bool ret = true;

    proposedGlobalClock = 0;
    core::BasicTime _proposedGlobalClock;

    foreach (const Arc* arc, inputArcs)
    {
        Expression* expr = dynamic_cast<Expression* >(
            arc->getExpression());
        const QList<VariableName> names = expr->getUserVariables().keys();

        if (names.size() > 0)
        {
            VariableName var = names.at(0);

            BasicTime _globalClock = globalClock;
            _globalClock.add(transition->getDelay().getTime());

            ret = BAH->bindFreeVariable(var, arc, binding, _globalClock,
                _proposedGlobalClock);

            if (_proposedGlobalClock > proposedGlobalClock)
            {
                proposedGlobalClock = _proposedGlobalClock;
            }

            if (!ret)
            {
                break;
            }
        }
    }

    return ret;
}
